package admin.data.config;

import java.util.Collections;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import systems.ConfigSystem;

import models.config.ServiceConfigModel;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;

public class ServiceConfigData {
	private Objectify ofy;
	
	private Cache cache = null;
	
	private String prefix = "service_";
	
	public ServiceConfigData() {
		try {
			ObjectifyService.register(ServiceConfigModel.class);
		} catch (Exception e) {
			//e.printStackTrace();
		}
		
		try {
            cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
        } catch (CacheException e) {
           //e.printStackTrace();
        }
		
        ObjectifyOpts opts = new ObjectifyOpts().setSessionCache(true);
		ofy = ObjectifyService.begin(opts);
	}
	
	public ServiceConfigModel getConfig(long id) {
		ServiceConfigModel config = new ServiceConfigModel();
		if (cache != null && cache.containsKey(prefix + Long.toString(id))) {
			config = (ServiceConfigModel) cache.get(prefix + Long.toString(id));
		} else {
			try {
				config = ofy.get(new Key<ServiceConfigModel>(ServiceConfigModel.class, id));
				cache.put(prefix + Long.toString(id), config);
			} catch (Exception e) {
				config = null;
			}
		}
		return config;
	}
	
	public void insert(ServiceConfigModel config) {
		ConfigSystem.setServiceConfigs(config);
		if (cache != null) {
			cache.put(prefix + Long.toString(config.getId()), config);
		}
		ofy.put(config);
	}
	
	public void delete(ServiceConfigModel config) {
		if (cache != null && cache.containsKey(prefix + Long.toString(config.getId()))) {
			cache.remove(prefix + Long.toString(config.getId()));
		}
		ofy.delete(config);
	}
}
